'use client'

import { useState, useEffect } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Calendar, Clock, Trophy, Users, Search, Filter } from 'lucide-react'
import { competitionsApi } from '@/lib/api'
import Link from 'next/link'

interface Competition {
  id: number
  title: string
  short_description?: string
  type: string
  category: string
  tags: string[]
  difficulty: string
  platform: string
  prize_pool: number
  start_date: string
  end_date: string
  submission_deadline?: string
  registration_end: string
  status: string
  participants_count: number
  max_team_size: number
  banner_image?: string
  external_url?: string
  is_featured: boolean
  view_count: number
  slug: string
}

const difficultyColors = {
  beginner: 'bg-green-100 text-green-800',
  intermediate: 'bg-yellow-100 text-yellow-800',
  advanced: 'bg-orange-100 text-orange-800',
  expert: 'bg-red-100 text-red-800'
}

const statusColors = {
  draft: 'bg-gray-100 text-gray-800',
  published: 'bg-blue-100 text-blue-800',
  ongoing: 'bg-green-100 text-green-800',
  ended: 'bg-red-100 text-red-800',
  cancelled: 'bg-red-100 text-red-800'
}

export default function CompetitionsPage() {
  const [competitions, setCompetitions] = useState<Competition[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [searchTerm, setSearchTerm] = useState('')
  const [selectedCategory, setSelectedCategory] = useState('all')
  const [selectedDifficulty, setSelectedDifficulty] = useState('all')
  const [selectedStatus, setSelectedStatus] = useState('all')
  const [selectedTimeFilter, setSelectedTimeFilter] = useState('all')
  const [sortBy, setSortBy] = useState('start_date')
  const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('desc')

  useEffect(() => {
    fetchCompetitions()
  }, [])

  const fetchCompetitions = async () => {
    try {
      setLoading(true)
      setError(null)
      // 传递size参数获取更多数据，设置为100以确保获取所有数据
      const response = await competitionsApi.getCompetitions({ size: 100 })
      setCompetitions(response || [])
    } catch (error) {
      console.error('获取竞赛列表失败:', error)
      setError('获取竞赛列表失败，请稍后重试')
    } finally {
      setLoading(false)
    }
  }

  // 获取竞赛的实际状态
  const getCompetitionStatus = (competition: Competition) => {
    const now = new Date()
    const startDate = new Date(competition.start_date)
    const endDate = new Date(competition.end_date)
    const submissionDeadline = competition.submission_deadline ? new Date(competition.submission_deadline) : null
    
    if (now < startDate) {
      return 'upcoming' // 即将开始
    } else if (now >= startDate && now <= endDate) {
      if (submissionDeadline && now <= submissionDeadline) {
        return 'submission_open' // 可提交
      } else if (submissionDeadline && now > submissionDeadline) {
        return 'submission_closed' // 提交已截止但竞赛未结束
      } else {
        return 'ongoing' // 进行中
      }
    } else {
      return 'ended' // 已结束
    }
  }

  const filteredCompetitions = competitions.filter(competition => {
    const matchesSearch = competition.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         competition.category.toLowerCase().includes(searchTerm.toLowerCase())
    const matchesCategory = selectedCategory === 'all' || competition.category === selectedCategory
    const matchesDifficulty = selectedDifficulty === 'all' || competition.difficulty === selectedDifficulty
    const matchesStatus = selectedStatus === 'all' || competition.status === selectedStatus
    
    // 时间筛选逻辑 - 使用实际状态而不是数据库状态
    let matchesTime = true
    const actualStatus = getCompetitionStatus(competition)
    
    if (selectedTimeFilter === 'upcoming') {
      matchesTime = actualStatus === 'upcoming'
    } else if (selectedTimeFilter === 'ongoing') {
      matchesTime = actualStatus === 'ongoing' || actualStatus === 'submission_closed'
    } else if (selectedTimeFilter === 'submission_open') {
      matchesTime = actualStatus === 'submission_open'
    } else if (selectedTimeFilter === 'ended') {
      matchesTime = actualStatus === 'ended'
    }
    
    return matchesSearch && matchesCategory && matchesDifficulty && matchesStatus && matchesTime
  })

  // 排序逻辑
  const sortedCompetitions = [...filteredCompetitions].sort((a, b) => {
    let aValue: any, bValue: any
    
    switch (sortBy) {
      case 'start_date':
        aValue = new Date(a.start_date).getTime()
        bValue = new Date(b.start_date).getTime()
        break
      case 'end_date':
        aValue = new Date(a.end_date).getTime()
        bValue = new Date(b.end_date).getTime()
        break
      case 'prize_pool':
        aValue = a.prize_pool
        bValue = b.prize_pool
        break
      case 'participants_count':
        aValue = a.participants_count
        bValue = b.participants_count
        break
      case 'difficulty':
        const difficultyOrder = { 'beginner': 1, 'intermediate': 2, 'advanced': 3, 'expert': 4 }
        aValue = difficultyOrder[a.difficulty as keyof typeof difficultyOrder] || 0
        bValue = difficultyOrder[b.difficulty as keyof typeof difficultyOrder] || 0
        break
      case 'title':
        aValue = a.title.toLowerCase()
        bValue = b.title.toLowerCase()
        break
      default:
        return 0
    }
    
    if (sortOrder === 'asc') {
      return aValue > bValue ? 1 : aValue < bValue ? -1 : 0
    } else {
      return aValue < bValue ? 1 : aValue > bValue ? -1 : 0
    }
  })

  const categories = [...new Set(competitions.map(c => c.category))]

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'short',
      day: 'numeric'
    })
  }

  const formatPrize = (amount: number) => {
    if (amount >= 10000) {
      return `¥${(amount / 10000).toFixed(1)}万`
    }
    return `¥${amount.toLocaleString()}`
  }

  if (loading) {
    return (
      <div className="container mx-auto px-4 py-8">
        <div className="flex items-center justify-center min-h-[400px]">
          <div className="text-center">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
            <p className="text-gray-600">加载竞赛数据中...</p>
          </div>
        </div>
      </div>
    )
  }

  if (error) {
    return (
      <div className="container mx-auto px-4 py-8">
        <div className="flex items-center justify-center min-h-[400px]">
          <div className="text-center">
            <div className="text-red-500 mb-4">
              <Trophy className="h-16 w-16 mx-auto" />
            </div>
            <h3 className="text-lg font-medium text-gray-900 mb-2">加载失败</h3>
            <p className="text-gray-600 mb-4">{error}</p>
            <Button onClick={fetchCompetitions}>重试</Button>
          </div>
        </div>
      </div>
    )
  }

  return (
    <div className="container mx-auto px-4 py-8">
      {/* 页面标题 */}
      <div className="mb-8">
        <h1 className="text-3xl font-bold text-gray-900 mb-2">竞赛中心</h1>
        <p className="text-gray-600">发现精彩的编程竞赛，提升技能，赢取奖励</p>
      </div>

      {/* 搜索和筛选 */}
      <div className="mb-8 space-y-4">
        <div className="flex flex-col md:flex-row gap-4">
          <div className="flex-1 relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 h-4 w-4" />
            <Input
              placeholder="搜索竞赛名称或分类..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              onKeyDown={(e) => {
                if (e.key === 'Enter') {
                  e.preventDefault() // 阻止回车键提交表单
                }
              }}
              className="pl-10"
            />
          </div>
          <div className="flex gap-2">
            <Select value={selectedCategory} onValueChange={setSelectedCategory}>
              <SelectTrigger className="w-[150px]">
                <SelectValue placeholder="分类" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">全部分类</SelectItem>
                {categories.map(category => (
                  <SelectItem key={category} value={category}>{category}</SelectItem>
                ))}
              </SelectContent>
            </Select>
            
            <Select value={selectedDifficulty} onValueChange={setSelectedDifficulty}>
              <SelectTrigger className="w-[120px]">
                <SelectValue placeholder="难度" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">全部难度</SelectItem>
                <SelectItem value="beginner">初级</SelectItem>
                <SelectItem value="intermediate">中级</SelectItem>
                <SelectItem value="advanced">高级</SelectItem>
                <SelectItem value="expert">专家</SelectItem>
              </SelectContent>
            </Select>

            <Select value={selectedStatus} onValueChange={setSelectedStatus}>
              <SelectTrigger className="w-[120px]">
                <SelectValue placeholder="状态" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">全部状态</SelectItem>
                <SelectItem value="published">已发布</SelectItem>
                <SelectItem value="ongoing">进行中</SelectItem>
                <SelectItem value="ended">已结束</SelectItem>
              </SelectContent>
            </Select>

            <Select value={selectedTimeFilter} onValueChange={setSelectedTimeFilter}>
              <SelectTrigger className="w-[140px]">
                <SelectValue placeholder="时间筛选" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">全部时间</SelectItem>
                <SelectItem value="upcoming">即将开始</SelectItem>
                <SelectItem value="ongoing">正在进行</SelectItem>
                <SelectItem value="submission_open">可提交</SelectItem>
                <SelectItem value="ended">已结束</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </div>
        
        {/* 排序选择器 */}
        <div className="flex items-center gap-2">
          <span className="text-sm text-gray-600">排序:</span>
          <Select value={sortBy} onValueChange={setSortBy}>
            <SelectTrigger className="w-[140px]">
              <SelectValue placeholder="排序字段" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="start_date">开始时间</SelectItem>
              <SelectItem value="end_date">结束时间</SelectItem>
              <SelectItem value="prize_pool">奖金池</SelectItem>
              <SelectItem value="participants_count">参与人数</SelectItem>
              <SelectItem value="difficulty">难度</SelectItem>
              <SelectItem value="title">标题</SelectItem>
            </SelectContent>
          </Select>
          <Select value={sortOrder} onValueChange={(value: 'asc' | 'desc') => setSortOrder(value)}>
            <SelectTrigger className="w-[100px]">
              <SelectValue placeholder="排序" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="desc">降序</SelectItem>
              <SelectItem value="asc">升序</SelectItem>
            </SelectContent>
          </Select>
        </div>
      </div>

      {/* 竞赛列表 */}
      {sortedCompetitions.length === 0 ? (
        <div className="text-center py-12">
          <div className="text-gray-400 mb-4">
            <Trophy className="h-16 w-16 mx-auto" />
          </div>
          <h3 className="text-lg font-medium text-gray-900 mb-2">暂无竞赛</h3>
          <p className="text-gray-600">当前没有符合条件的竞赛，请调整筛选条件或稍后再试</p>
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {sortedCompetitions.map((competition) => (
            <Card key={competition.id} className="hover:shadow-lg transition-shadow duration-200">
              <CardHeader className="pb-3">
                <div className="flex items-start justify-between">
                  <div className="flex-1">
                    <CardTitle className="text-lg mb-2 line-clamp-2">
                      {competition.title}
                    </CardTitle>
                    <div className="flex items-center gap-2 mb-2">
                      <Badge 
                        variant="secondary" 
                        className={difficultyColors[competition.difficulty as keyof typeof difficultyColors]}
                      >
                        {competition.difficulty === 'beginner' && '初级'}
                        {competition.difficulty === 'intermediate' && '中级'}
                        {competition.difficulty === 'advanced' && '高级'}
                        {competition.difficulty === 'expert' && '专家'}
                      </Badge>
                      <Badge 
                        variant="outline"
                        className={(() => {
                          const actualStatus = getCompetitionStatus(competition)
                          switch(actualStatus) {
                            case 'upcoming': return 'bg-blue-100 text-blue-800'
                            case 'ongoing': return 'bg-green-100 text-green-800'
                            case 'submission_open': return 'bg-yellow-100 text-yellow-800'
                            case 'submission_closed': return 'bg-orange-100 text-orange-800'
                            case 'ended': return 'bg-red-100 text-red-800'
                            default: return 'bg-gray-100 text-gray-800'
                          }
                        })()} 
                      >
                        {(() => {
                          const actualStatus = getCompetitionStatus(competition)
                          switch(actualStatus) {
                            case 'upcoming': return '即将开始'
                            case 'ongoing': return '进行中'
                            case 'submission_open': return '可提交'
                            case 'submission_closed': return '提交截止'
                            case 'ended': return '已结束'
                            default: return '未知状态'
                          }
                        })()}
                      </Badge>
                      {competition.is_featured && (
                        <Badge variant="default" className="bg-yellow-500 text-white">
                          精选
                        </Badge>
                      )}
                    </div>
                  </div>
                </div>
                <CardDescription className="line-clamp-2">
                  {competition.short_description || '暂无描述'}
                </CardDescription>
              </CardHeader>
              
              <CardContent className="space-y-4">
                {/* 竞赛信息 */}
                <div className="space-y-2 text-sm text-gray-600">
                  <div className="flex items-center gap-2">
                    <Trophy className="h-4 w-4" />
                    <span>奖金: {formatPrize(competition.prize_pool)}</span>
                  </div>
                  <div className="flex items-center gap-2">
                    <Users className="h-4 w-4" />
                    <span>{competition.participants_count} 人参与</span>
                  </div>
                  <div className="flex items-center gap-2">
                    <Calendar className="h-4 w-4" />
                    <span>开始: {formatDate(competition.start_date)}</span>
                  </div>
                  {competition.submission_deadline && (
                    <div className="flex items-center gap-2">
                      <Clock className="h-4 w-4" />
                      <span>提交截止: {formatDate(competition.submission_deadline)}</span>
                    </div>
                  )}
                  <div className="flex items-center gap-2">
                    <Calendar className="h-4 w-4" />
                    <span>竞赛结束: {formatDate(competition.end_date)}</span>
                  </div>
                  <div className="flex items-center gap-2">
                    <Clock className="h-4 w-4" />
                    <span>报名截止: {formatDate(competition.registration_end)}</span>
                  </div>
                </div>

                {/* 标签 */}
                <div className="flex flex-wrap gap-1">
                  {competition.tags.slice(0, 3).map((tag, index) => (
                    <Badge key={index} variant="outline" className="text-xs">
                      {tag}
                    </Badge>
                  ))}
                  {competition.tags.length > 3 && (
                    <Badge variant="outline" className="text-xs">
                      +{competition.tags.length - 3}
                    </Badge>
                  )}
                </div>

                {/* 操作按钮 */}
                <div className="flex gap-2 pt-2">
                  <Button asChild className="flex-1">
                    <Link href={`/competitions/${competition.id}`}>
                      查看详情
                    </Link>
                  </Button>
                  {competition.external_url && (
                    <Button variant="outline" asChild>
                      <a href={competition.external_url} target="_blank" rel="noopener noreferrer">
                        外部链接
                      </a>
                    </Button>
                  )}
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}
    </div>
  )
}